<script setup lang="ts">
import * as echarts from 'echarts'
import { ECharts, EChartsOption } from 'echarts'
import { EChartsUtil, getBarStyle } from '@utils/echarts'
import { Cell } from '@antv/x6'
import { FnOperationControl } from '@utils/object-util/periodic-execution/FnOperationControl'
import { recentDate } from '@utils/moment'
import { getAlarmStatisticsBySceneId } from '@/api/alarm'

const barChartRef = shallowRef<HTMLDivElement>()
const barChart = shallowRef<ECharts>()

const getNode = inject<{(): Cell }>('getNode')
const currentNode = getNode()
const dataConfig = currentNode.data.dataConfig
const { echartsOptions, echartsConfig } = dataConfig
onMounted(() => {
  initChart()
  // currentNode.data.dataConfig.updateChart = (e) => {
  //   console.log(123)
  // }
  barChart.value.setOption({
    xAxis: [{
      data: ['设备一', '设备二', '设备三', '设备四', '设备五', '设备六']
    }],
    series: [{
      data: [123, 123, 12, 123, 23, 12, 345, 121]
    }]
  } as EChartsOption)
})
onBeforeUnmount(() => {
  operationControl && operationControl.stop()
})

const runTypeDic = {
  alarmStatistics: {
    run: alarmStatistics,
    name: '报警统计'
  }
}

function run (data: any) {
  sceneId = data.sceneId
  dataType = currentNode.data.dataConfig.dataOption.dataType
  if (dataType) {
    runTypeDic[dataType].run()
  } else {
    barChart.value.setOption({
      yAxis: [{ name: '' }],
      xAxis: [{ data: [] }],
      series: [{ name: '--', data: [] }]
    } as EChartsOption)
  }
}

// region TODO 柱状图数据
// 场景Id
let sceneId = null
let dataType = ''
let operationControl: FnOperationControl = null
// 报警统计
function alarmStatistics () {
  operationControl = new FnOperationControl({
    async fn () {
      const { dataRange } = currentNode.data.dataConfig.dataOption
      const [startTime, endTime] = recentDate(dataRange - 1)
      const res = await getAlarmStatisticsBySceneId({
        groupId: sceneId,
        startTime: startTime + ' 00:00:00',
        endTime: endTime + ' 23:59:59'
      })
      res.result().then((rdata) => {
        const data = rdata.data || []
        const xAxis = []
        const seriesData = []
        for (let i = 0, len = data.length; i < len; i++) {
          xAxis.push(data[i].deviceName)
          seriesData.push(data[i].alarmCount)
        }
        barChart.value.setOption({
          yAxis: [{ name: '次', minInterval: 1 }],
          xAxis: [{ data: xAxis }],
          series: [{
            name: runTypeDic[dataType].name,
            data: seriesData
          }]
        } as EChartsOption)
      })
    },
    rightRun: true,
    timeout: 1800000
  })
}
// endregion

// region TODO 更新ChartOptions
function updateChartAttrs (e) {
  dataConfig.echartsOptions = e
  barChart.value.setOption(e)
}
// endregion

// region TODO 更新文本颜色
function updateChartText (e) {
  echartsConfig.textColor = e
  barChart.value.setOption({
    legend: { textStyle: { color: e.color } },
    yAxis: [{
      nameTextStyle: { color: e.color },
      axisLabel: { color: e.color }
    }],
    xAxis: [{
      axisLabel: { color: e.color },
      axisLine: { lineStyle: { color: e.color } },
      axisTick: { lineStyle: { color: e.color } }
    }]
  } as EChartsOption)
}
// endregion

// region TODO 更新分割线颜色
function updateSplitLineColor (e) {
  echartsConfig.splitLine = e
  barChart.value.setOption({
    yAxis: [{
      splitLine: {
        lineStyle: {
          color: [e.color]
        }
      }
    }]
  } as EChartsOption)
}
// endregion

// region TODO 更新渐变颜色
function updateChartArea (e?) {
  if (e) echartsConfig.area = e
  const { show, color1, color2 } = echartsConfig.area
  barChart.value.setOption({
    series: [{
      itemStyle: {
        color: show ? EChartsUtil.getLinearGradient(color1, color2) : color1
      }
    }]
  } as EChartsOption)
}
// endregion

// region TODO 初始化Chart
function initChart () {
  barChart.value = echarts.init(barChartRef.value)
  barChart.value.setOption(getBarStyle({
    color: echartsConfig.area.color1,
    unit: '单位',
    name: '名称',
    area: echartsConfig.area.show,
    areaColor: echartsConfig.area.color2
  }).setLegend(echartsOptions.legend)
    .setTooltip(echartsOptions.tooltip)
    .getResult())
  barChart.value.setOption({
    toolbox: echartsOptions.toolbox,
    legend: {
      textStyle: { color: echartsConfig.textColor.color }
    },
    xAxis: [{
      axisLabel: { color: echartsConfig.textColor.color },
      axisLine: { lineStyle: { color: echartsConfig.textColor.color } },
      axisTick: { lineStyle: { color: echartsConfig.textColor.color } }
    }],
    yAxis: [{
      nameTextStyle: { color: echartsConfig.textColor.color },
      axisLabel: { color: echartsConfig.textColor.color },
      splitLine: {
        lineStyle: {
          color: [echartsConfig.splitLine.color]
        }
      }
    }]
  })
  EChartsUtil.addResizeListener(barChart.value)
}
onBeforeUnmount(() => {
  EChartsUtil.removeResizeListener(barChart.value)
})
// endregion

currentNode.data.expose = {
  updateChartAttrs,
  updateChartText,
  updateChartArea,
  updateSplitLineColor,
  run
}
</script>

<template>
  <div ref="barChartRef" style="width: 100%;height: 100%" />
</template>

<style scoped lang="scss">

</style>
